package com.useeinfo.oa.modules.security.extend;

import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.CommonSugar;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.security.biz.SystemAuthorityBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemAuthority;
import com.useeinfo.oa.modules.security.entity.SystemRole;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * Author: 居泽平  Date: 14-3-27, 下午3:42
 */
public class MyUserDetailsService implements UserDetailsService {

    private final static Logger logger = LoggerFactory.getLogger(MyUserDetailsService.class);

    private SystemUserBiz systemUserBiz;

    private SystemAuthorityBiz systemAuthorityBiz;

    private EnterpriseBiz enterpriseBiz;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        // 获取角色具备权限
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        // 使用User服务类查询数据用户是否存在,如不存在或密码错误则抛出对应的异常
        SystemUser user = this.systemUserBiz.getByUserAccount(username, true);
        if (null == user) {
            throw new UsernameNotFoundException("用户/密码错误,请重新输入!");
        }
        logger.info("user info [{}]", user.getUserName());

        if ("admin".equals(user.getOperationRole())) {
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_EDIT"));//企业编辑权限
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_LIST"));//企业列表权限
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_SYSTEM_USER_LIST"));//企业用户和平台用户列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_SYSTEM_USER_EDIT"));//企业用户和平台用户编辑
        }

        /*if ("enterprise".equals(user.getOperationRole())) {
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_AREA_EDIT"));//区域管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_AREA_LIST"));//区域管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_GROUP_EDIT"));//设备分组管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_GROUP_LIST"));//设备分组管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_CAT_EDIT"));//设备分类管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_CAT_LIST"));//设备分类管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_EDIT"));//设备管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_LIST"));//设备管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_IMPORT_EDIT"));//设备导入管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_IMPORT_LIST"));//设备导入管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_REPAIR_ORDER_LIST"));//维修单管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_REPAIR_ORDER_EDIT"));//维修单管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_REPAIR_ORDER_AUDIT_LIST"));//审批管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_REPAIR_ORDER_AUDIT_EDIT"));//审批管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_PLANNER_ORDER_LIST"));//维护保养——计划工单——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_PLANNER_LOG_LIST"));//维护保养——计划工单——操作日志列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_PLANNER_ORDER_ASSIGN"));//维护保养——计划工单——指派功能
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_PLANNER_ORDER_OPERATE"));//维护保养——计划工单——开始计划停止计划
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_PLANNER_ORDER_DATE"));//维护保养——计划工单——强制生成指定日实施单
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_PLANNER_ORDER_RELATIVE"));//维护保养——计划工单——查看生成工单
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_PLANNER_ORDER_IMPORT"));//维护保养——计划工单——导入计划
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_PLANNER_ORDER_EXPORT"));//维护保养——计划工单——导出年度计划
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_PLANNER_ORDER_EDIT"));//维护保养——计划工单——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_WORKING_HOURS_LIST"));//维护保养——工时管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_WORKING_HOURS_EDIT"));//维护保养——工时管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_MAINTAIN_TECHNOLOGY_LIST"));//维护保养——工艺管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_MAINTAIN_TECHNOLOGY_EDIT"));//维护保养——工艺管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_APPLICATION_SCENARIOS_LIST"));//维护保养——应用场景——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_MAINTAIN_ORDER_LIST"));//维护保养——工单管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_MAINTAIN_ORDER_EDIT"));//维护保养——工单管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_MAINTAIN_ORDER_LOG_LIST"));//维护保养——工单管理——操作日志列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_MAINTAIN_APPLY_LIST"));//维护保养——申请记录
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_MAINTAIN_AUDIT_LIST"));//维护保养——审批记录
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_MAINTAIN_ORDER_AUDIT_LIST"));//维护保养——审批列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_MAINTAINING_MAINTAIN_AUDIT_ORDER"));//维护保养——审批权限

            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_INSPECTION_TECHNOLOGY_LIST"));//巡检管理——工艺管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_INSPECTION_TECHNOLOGY_EDIT"));//巡检管理——工艺管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_INSPECTION_ORDER_LIST"));//巡检管理——工单管理——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_INSPECTION_ORDER_EDIT"));//巡检管理——工单管理——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_INSPECTION_ORDER_LOG_LIST"));//巡检管理——工单管理——操作日志列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_PLANNER_ORDER_LIST"));//维护保养——计划工单——查看列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_PLANNER_LOG_LIST"));//巡检管理——计划工单——操作日志列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_PLANNER_ORDER_ASSIGN"));//巡检管理——计划工单——指派功能
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_PLANNER_ORDER_OPERATE"));//巡检管理——计划工单——开始计划停止计划
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_PLANNER_ORDER_DATE"));//巡检管理——计划工单——强制生成指定日实施单
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_PLANNER_ORDER_RELATIVE"));//巡检管理——计划工单——查看生成工单
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_PLANNER_ORDER_IMPORT"));//巡检管理——计划工单——导入计划
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_PLANNER_ORDER_EXPORT"));//巡检管理——计划工单——导出年度计划
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_PLANNER_ORDER_EDIT"));//巡检管理——计划工单——新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_INS_APPLY_LIST"));//巡检管理——申请记录
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_INS_AUDIT_LIST"));//巡检管理——审批记录
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_INSPECTION_ORDER_AUDIT_LIST"));//巡检工单——审批列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_INSPECTION_AUDIT_ORDER"));//巡检管理——审批权限



            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_DATA_EDIT"));//设备资料--新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_DATA_LIST"));// 设备资料--列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_DATA_CAT_EDIT"));//资料类型--新增编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_DATA_CAT_LIST"));//资料类型--列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_DATA_LOG_LIST"));// 设备资料操作日志--列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_DATA_CAT_LOG_LIST"));// 资料类型操作日志--列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_TROUBLE_CAT_EDIT"));//故障分类管理
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_AUDIT_FLOW_EDIT"));//审批流管理
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_DICT_INFO_EDIT"));//数据字典管理
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_LIST"));//企业列表权限
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_PERSONNEL_LIST"));//人员列表——部门管理
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_PERSONNEL_EDIT"));//人员操作——部门管理
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_ORGANIZATION_LIST"));//部门列表——部门管理
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_ORGANIZATION_EDIT"));//部门编辑——部门管理
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_POSITION_LIST"));//岗位列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_POSITION_EDIT"));//岗位编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_AUDIT_FLOW_LIST"));//审批流管理
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_SYSTEM_USER_LIST"));//企业系统用户列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_SYSTEM_USER_EDIT"));//企业系统用户编辑

            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_ROLE_LIST"));//企业角色列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_ROLE_EDIT"));//企业角色编辑
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_PERIOD_INSTALL_LIST"));//周期列表
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_PERIOD_INSTALL_EDIT"));//周期设置
        }*/



        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        SessionKeyUtils.setSessionUser(request, user);
        if (!"admin".equals(user.getUserAccount())) {
            if (CollectionUtils.isEmpty(user.getEnterpriseSet())) {
                throw new UsernameNotFoundException("权限不足!");
            }
            Enterprise enterprise = user.getEnterpriseSet().iterator().next();
            SessionKeyUtils.setSessionEnterprise(request, enterprise);

            if ("enterprise".equals(user.getOperationRole())) {
                String authHql = "select obj from SystemAuthority obj left join obj.systemModule as sm where obj.deleteStatus is false and ( sm is null  or" +
                        " sm.applicationModuleId in ( select al.id from  ApplicationModule al" +
                        " where exists( select ep from al.enterpriseSet ep where ep.id="+enterprise.getId()+")))";
                List<SystemAuthority>authorityList = systemAuthorityBiz.hqlExcute(authHql);
                for(SystemAuthority systemAuthority:authorityList){
                    grantedAuthorities.add(new SimpleGrantedAuthority(systemAuthority.getAuthorityName()));
                }
            }
            String authHql = "select obj from SystemAuthority obj left join obj.systemModule as sm where obj.deleteStatus is false and ( sm is null  or" +
                    " sm.applicationModuleId in ( select al.id from  ApplicationModule al" +
                    " where exists( select ep from al.enterpriseSet ep where ep.id="+enterprise.getId()+")))" +
                    " and exists( select r from obj.roleSet r where r.id in ( select ure.systemRole.id from UserRoleEnterprise ure where " +
                    " ure.enterprise.id=" + enterprise.getId() + " and ure.systemUser.id =" + user.getId() + ")) ";
            List<SystemAuthority>authorityList = systemAuthorityBiz.hqlExcute(authHql);
            for(SystemAuthority systemAuthority:authorityList){
                grantedAuthorities.add(new SimpleGrantedAuthority(systemAuthority.getAuthorityName()));
            }
        }






        // 获取用户角色
      /*  SystemRole role = user.getSystemRole();

        Set<SystemAuthority> unionAuthorities = new HashSet<>();
        if (role != null) {
            logger.info("用户角色:[{}]", role.getRoleName());
            List<SystemAuthority> authorityList = systemAuthorityBiz.getAuthoritiesByRoleId(role.getId());
            unionAuthorities.addAll(authorityList);
        }

        *//*if (CollectionUtils.isEmpty(unionAuthorities) && !"admin".equals(user.getUserAccount())) {
            throw new UsernameNotFoundException("权限不足!");
        }*//*

        for (SystemAuthority auth : unionAuthorities) {
            logger.info("拥有权限:[{}]", auth.getAuthorityName());
            grantedAuthorities.add(new SimpleGrantedAuthority(auth.getAuthorityName()));
        }*/
        return new User(username, user.getUserPassword(), true, true, true, true, grantedAuthorities);
    }

    public void setSystemUserBiz(SystemUserBiz systemUserBiz) {
        this.systemUserBiz = systemUserBiz;
    }

    public void setSystemAuthorityBiz(SystemAuthorityBiz systemAuthorityBiz) {
        this.systemAuthorityBiz = systemAuthorityBiz;
    }
}